package resource

import (
	"gorm.io/gorm"
	"mallgo/internal/common/response"
	"mallgo/internal/resources/user/api/domain/request"
	userModel "mallgo/internal/resources/user/model"
	"time"
)

type UserResource struct {
	db *gorm.DB
}

func NewUserResource(db *gorm.DB) *UserResource {
	return &UserResource{db}
}

func (h *UserResource) Register(req *request.RegisterRequest) *response.ResponseObject {

	// 检查用户名是否已经存在
	var existingUser userModel.UserAccount

	if err := h.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
		return response.Error(500, "该用户名已经存在")
	}

	// 创建用户账户
	userAccount := userModel.UserAccount{
		Username: req.Username,
		AddDate:  time.Now(),
	}

	// 创建密码，假设没有加盐处理（可以根据需求进行加密）
	userPassword := userModel.UserPassword{
		Password: req.Password, // 这里应该加盐并加密
		AddDate:  time.Now(),
	}

	// 创建用户信息
	userInfo := userModel.UserInfo{
		Name:      req.Username,
		Phone:     req.Phone,
		AddDate:   time.Now(),
		BeginDate: time.Now(),
		LastDate:  time.Now(),
	}

	// 启动事务
	tx := h.db.Begin()
	if err := tx.Create(&userInfo).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建用户失败")
	}
	userPassword.UserID = userInfo.ID
	if err := tx.Create(&userPassword).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建密码失败")

	}
	userAccount.UserID = userInfo.ID
	if err := tx.Create(&userAccount).Error; err != nil {
		tx.Rollback()
		return response.Error(500, "创建用户账号失败")
	}

	// 提交事务
	tx.Commit()
	// 注册成功
	return response.Success(userInfo)
}
